package auth_middleware

import (
	response "go_service/common"
	"go_service/database/redis"
	"go_service/util/jwt"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware(c *gin.Context) {
	token := c.GetHeader("token")
	if token == "" {
		c.JSON(200, response.Error(401, "token不能为空"))
		c.Abort()
		return
	}
	username := jwt.ParseToken(token)
	if username == "" {
		c.JSON(200, response.Error(401, "token无效"))
		c.Abort()
		return
	}
	tokenInRedis := redis.GetKey(username)
	if tokenInRedis == "" {
		c.JSON(200, response.Error(401, "token无效"))
		c.Abort()
		return
	}
	if token != tokenInRedis {
		c.JSON(200, response.Error(401, "token无效"))
		c.Abort()
		return
	}
	if !redis.SetKey(username, token, 60*60) {
		c.JSON(200, response.Error(401, "token无效"))
		c.Abort()
		return
	}
	c.Next()
}
